package com.szewec.ps.greenDao.manager;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.github.yuweiguocn.library.greendao.MigrationHelper;
import com.szewec.ps.base.BaseApplication;
import com.szewec.ps.greenDao.dao.*;

import org.greenrobot.greendao.database.Database;

@SuppressWarnings("unused")
public class DaoManager {
    private static DaoManager mInstance;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;

    private DaoManager() {
        MyOpenHelper devOpenHelper = new MyOpenHelper(BaseApplication.getContext(), "ps-db", null);
        mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
        //去掉缓存
        mDaoSession.clear();
    }

    public DaoMaster getMaster() {
        return mDaoMaster;
    }

    public DaoSession getSession() {
        return mDaoSession;
    }

    public static DaoManager getInstance() {
        if (mInstance == null) {
            mInstance = new DaoManager();
        }
        return mInstance;
    }
    public class MyOpenHelper extends DaoMaster.OpenHelper {
        public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
            super(context, name, factory);
        }

        @Override
        public void onUpgrade(Database db, int oldVersion, int newVersion) {

            //把需要管理的数据库表DAO作为最后一个参数传入到方法中
            MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {

                @Override
                public void onCreateAllTables(Database db, boolean ifNotExists) {
                    DaoMaster.createAllTables(db, true);
                }

                @Override
                public void onDropAllTables(Database db, boolean ifExists) {
                    DaoMaster.dropAllTables(db, true);
                }
                //数据库升级,修改表时,需要保留数据的表,写在这里
            }
            );
        }
    }
}
